package handlers

import (
	"code.google.com/p/jesus-1496/auth/models"
	"code.google.com/p/jesus-1496/auth/sessionshelper"
	"code.google.com/p/jesus-1496/servererror"

	"github.com/gorilla/schema"

	"net/http"
)

type loginForm struct {
	Email    string `schema:"username"`
	Password string `schema:"password"`
}

var decoder = schema.NewDecoder() //Should be a package global

var loginSuccessHandler func(http.ResponseWriter, *http.Request) *servererror.ServerError

func LoginHandler(w http.ResponseWriter, r *http.Request) *servererror.ServerError {
	lf := new(loginForm)
	if err := r.ParseForm(); err != nil {
		return servererror.NewServerError(err, "Internal server error.", http.StatusInternalServerError)
	}

	if err := decoder.Decode(lf, r.Form); err != nil {
		return servererror.NewServerError(err, "Invalid form values given.", http.StatusInternalServerError)
	}

	user, err := models.LoadUser(lf.Email)
	if err != nil {
		return servererror.NewServerError(err, "Email address not found or incorrect password.", http.StatusOK)
	}

	err = user.Authenticate(lf.Password)
	if err != nil {
		return servererror.NewServerError(err, "Email address not found or incorrect password.", http.StatusOK)
	}
	logger.Printf("Authentication successful for %s.\n", lf.Email)

	//Get rid of password immediately for security reasons
	lf.Password = ""

	if err = sessionshelper.LogUserIn(w, r, user); err != nil {
		return servererror.NewServerError(err, "Internal server error.", http.StatusOK)
	}

	return loginSuccessHandler(w, r)
}

func SetLoginSuccessHandler(f func(http.ResponseWriter, *http.Request) *servererror.ServerError) {
	loginSuccessHandler = f
}
